package com.example.futureai.service.impl;

import com.example.futureai.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @ClassName: RedisServiceImpl
 * @Description:
 * @Author: YourName
 * @Date: 2025/2/24
 */

@Service
@Slf4j
public class RedisServiceImpl implements RedisService, AutoCloseable {
    @Autowired
    @Qualifier("myJedisPool")
    private JedisPool jedisPool;

    private Jedis jedis;

    @Override
    public boolean hasKey(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.exists(key);
        } catch (Exception e) {
            log.error("Redis hasKey error, key: {}", key, e);
            throw new RuntimeException("Redis operation failed", e);
        }
    }

    @Override
    public void setObject(String key, JSONObject docJson) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.set(key, docJson.toString());
        } catch (Exception e) {
            log.error("Redis setObject error, key: {}", key, e);
            throw new RuntimeException("Redis operation failed", e);
        }
    }

    @Override
    public void setObject(String key, String value, long time) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.setex(key, time, value);
        } catch (Exception e) {
            log.error("Redis setObject with timeout error, key: {}", key, e);
            throw new RuntimeException("Redis operation failed", e);
        }
    }

    @Override
    public void setObjectRdb(String key, JSONObject docJson) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.set(key, docJson.toString());
            jedis.save();
        } catch (Exception e) {
            log.error("Redis setObjectRdb error, key: {}", key, e);
            throw new RuntimeException("Redis operation failed", e);
        }
    }

    @Override
    public void save() {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.save();
        } catch (Exception e) {
            log.error("Redis save error", e);
            throw new RuntimeException("Redis operation failed", e);
        }
    }

    @Override
    public String get(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.get(key);
        } catch (Exception e) {
            log.error("Redis get error, key: {}", key, e);
            throw new RuntimeException("Redis operation failed", e);
        }
    }


    @Override
    public void close() {
        if (jedisPool != null && !jedisPool.isClosed()) {
            jedisPool.close();
        }
    }
}